<?php
//设备管理
namespace app\ausadmin\controller;
use app\ausadmin\controller\Common;
use think\Request;
use think\Loader;
use think\Db;
use think\Cache;
use think\Session;
use think\Cookie;
use think\Controller;
use think\Config;
use Godok\Org\Adminauth;
use mlsmt\Cabinet\Send;
use think\Validate;

class Equipment extends Common{


    /**
     *导入机柜
     *
     */
    public function importCabinet(){
        if(!empty($_FILES)){
            foreach($_FILES as $k=>$v){
                $keyname=$k;//获取提交文件数组的键名;
            }
            $tmp_file = $_FILES[$keyname]['tmp_name'];    //临时文件名
            $file_types = explode('.',$_FILES[$keyname]['name']); //  拆分文件名
            $file_type = $file_types [count ( $file_types ) - 1];   //  文件类型
            if($file_type == 'xls' || $file_type == 'xlsx'|| $file_type == 'csv'){
                /*上传文件*/
                $file = request()->file($keyname);
                $info=$file->move(ROOT_PATH . 'public' . DS . 'uploads'.DS.'excel');
                if(!$info){
                    $this->error($file->getError());
                }
                //获取上传文件目录
                $file_name=ROOT_PATH . 'public' . DS . 'uploads'.DS.'excel'.DS.$info->getSaveName();
                //vendor("PHPExcel.PHPExcel");
                //vendor("excel.PHPExcel");
                Loader::import('PHPExcel.PHPExcel');
                Loader::import('PHPExcel.PHPExcel.IOFactory');
                Loader::import('PHPExcel.PHPExcel.IOFactory.PHPExcel_IOFactory');
                $PHPExcel = new \PHPExcel();
                if($file_type=='xlsx'){
                    //设置以Excel5格式(Excel97-2003工作簿)
                    Loader::import('PHPExcel.PHPExcel.Reader.Excel2007');
                    $objReader=new \PHPExcel_Reader_Excel2007();
                    // $objReader=\PHPExcel_IOFactory::createReader('Excel2007');
                    //\PHPExcel_IOFactory::createReader('Excel5');
                }
                if($file_type=='xls'){
                    Loader::import('PHPExcel.PHPExcel.Reader.Excel5');
                    $objReader= new \PHPExcel_Reader_Excel5();
                    //$objReader=\PHPExcel_IOFactory::createReader('Excel5');
                }
                /*if($file_type=='csv'){
                    $objReader=\PHPExcel_IOFactory::createReader('CSV');
                }*/
                // 载入excel文件
                $objPHPExcel = $objReader->load($file_name,$encode='utf-8');
                $sheet = $objPHPExcel->getSheet(0); // 读取第一個工作表
                $highestRow = $sheet->getHighestRow(); // 取得总行数
                //var_dump($highestRow); die;
                $j=0;
                $repeat = [];
                $oid = input('oid');
                for($i=2;$i<=$highestRow;$i++){
                    $data=null;
                    $data['cabinet_id']=$objPHPExcel->getActiveSheet()->getCell("A".$i)->getValue();
                    if(is_object($data['cabinet_id']))  $data['cabinet_id']= $data['cabinet_id']->__toString();
                    $data['model']=$objPHPExcel->getActiveSheet()->getCell("B".$i)->getValue();
                    $data['devicenum']=$objPHPExcel->getActiveSheet()->getCell("C".$i)->getValue();
                    $data['networking_card']=$objPHPExcel->getActiveSheet()->getCell("D".$i)->getValue();
                    if(is_object($data['networking_card']))  $data['networking_card']= $data['networking_card']->__toString();
                    $data['oid'] = $oid;
                    $data['sid'] = '';
                    $data['status'] =1;
                    $data['create_user'] = session('adminid');
                    $data['create_time'] = time();
                    $data['is_delete'] = 1;
                    //var_dump($data);die;
                    $check = Db::name('charecabinet')->where('cabinet_id',$data['cabinet_id'])->where('status',1)->find();
                    /*if($check){
                        return ['code'=>-1050, 'msg'=>'导入失败！表中有重复数据'.$check['cabinet_id']];
                    }
                    if(Db::name('charecabinet')->insert($data)){
                        $j++;
                    }*/
                    if($check){
                        $repeat[] = Db::name('charecabinet')->where(['is_delete'=>1,'cabinet_id'=>$data['cabinet_id']])->value('cabinet_id');
                    }else{
                        if(Db::name('portablebattery')->insert($data)){
                            $j++;
                        }
                    }

                }
                //$this->success('导入成功！本次导入记录数量：'.$j);
                $oid = 1;$m = 'ausadmin'; $c = 'Operator'; $action="cabinet"; $uid=session('adminid'); $querystring = input('oid').'运批量导入机柜信息';
                $ip = get_ip();$os = get_os();
                set_logs($oid,$m,$c,$action,$uid,$querystring,$ip,$os);
                @unlink($file_name);
//                return ['code'=>0, 'msg'=>'导入成功！本次导入机柜数量：'.$j];
                return ['code'=>0, 'msg'=>'本次导入机柜数量为：' . $j . '；因表中重复导入失败的：' . implode(' ', $repeat)];
            }else{
                //格式不正确提示
                return ['code'=>-1050, 'msg'=>'请上传正确的excel格式的文件！'];
            }
        }/*else{
            return $this->fetch();
        }*/
        $id =  Request::instance()->get('id','','number_int');

        if(!empty($id)){
            $oid = $id;
            $this->assign('oid',$oid);
            return $this->fetch();
        }else{
            die('非法访问！');
        }

    }



    public function index($sid=""){
        $pages = 20;
        $sid =  Request::instance()->get('sid','','number_int');
        $pageParam    = ['query' =>[]];//按分页条件查找
        $where = 'a.is_delete=1';
        $where2= 'b.is_delete=1';
        if($sid!=''){
            $where .= ' AND a.sid = '.$sid;
            $pageParam['query']['sid'] = $sid;
        }
        //判断是否有表单提交的数据
        if(!empty(input('name'))){
            
            $where .= ' AND b.name LIKE '."'%".input('name')."%' ";
            $pageParam['query']['b.name'] = input('name');
        }

        if(!empty(input('area'))){
            $where .= ' AND b.area LIKE '."'%".input('area')."%' ";
            $pageParam['query']['b.area'] = input('area');
        }

        if(!empty(input('cabinet_id'))){
            $where .= ' AND a.cabinet_id LIKE '."'%".input('cabinet_id')."%' ";
            $pageParam['query']['a.cabinet_id'] = input('cabinet_id');
        }
        $s = 'seller';//商户表
        $list = DB::name('charecabinet')
              ->alias('a')
              ->join("$s b",'a.sid = b.id')
              ->field('a.id,a.cabinet_id,a.model,a.mode,a.oid,a.status,b.name,b.area,b.addr')
              ->where($where)
              ->order('a.create_time desc')	
              ->paginate($pages,false, $pageParam);
        $data = $list->all();	
        $time = time();  
        foreach ($data  as $k=>$v) {
            $data2 = Cache::store('redis')->get($v['cabinet_id']);
            isset($data2['heartbeattime'])?$v['heartbeattime']=$data2['heartbeattime']:'';
            isset($data2['clientip'])?$v['clientip']=$data2['clientip']:'';
            if(isset($data2['heartbeattime'])){
                $v['clientip'] = $data2['clientip'];
                $v['heartbeattime'] = $data2['heartbeattime'];
                $v['times'] = $time - $data2['heartbeattime'];
                $list[$k] = $v;
            }else{
                $v['clientip'] = '';
                $v['heartbeattime'] ='';
                $v['times'] = '';
                $list[$k] = $v;
            }
        }
        if(!empty(input('cabinet_id'))){
            $where .= ' AND a.cabinet_id LIKE '."'%".input('cabinet_id')."%' ";
            $pageParam['query']['cabinet_id'] = input('cabinet_id');
            $this->assign('cabinet_id',input('cabinet_id'));
        }
        if(!empty(input('name'))){

            $where2 .= ' AND b.name LIKE '."'%".input('name')."%' ";
            $this->assign('name',input('name'));
            $pageParam['query']['name'] = input('name');
        }
        if(!empty(input('oid'))){//直营商1/代理商大于1
            $where .= " AND a.oid = ".(int)input('oid');
            $where2 .= ' AND b.oid = '.(int)input('oid');
            $pageParam['query']['oid'] = input('oid');
            $this->assign('oid',input('oid'));
        }
        if(!empty(input('area'))){
            $where2 .= ' AND b.area LIKE '."'%".input('area')."%' ";
            $pageParam['query']['area'] = input('area');
            $this->assign('area',input('area'));
        }
        if((!empty(input('name'))) or (!empty(input('area')))){
            $s = 'seller';//商户表
            $list = DB::name('charecabinet')
                ->alias('a')
                ->join("$s b",'a.sid = b.id')
                ->join('operator c', 'b.oid = c.id')
                ->field('a.id,a.cabinet_id,a.model,a.mode,a.status,b.name,b.area,b.addr,a.oid,c.name as oname')
                ->where('a.is_delete',1)
                ->where($where2)
                ->order('a.create_time desc')
                ->paginate($pages,false, $pageParam);
        }else{
            $list = Db::name('charecabinet')
                ->alias('a')
                ->join('operator b','a.oid=b.id')
                ->where($where)
                ->field('a.*,b.name as oname')
                ->order('a.create_time desc')
                ->paginate($pages,false, $pageParam);
            $data2 = $list->all();
            foreach ($data2 as $k => $v) {
                $ret = Db::name('seller')
                    ->where('id',$v['sid'])
                    ->where('is_delete',1)
                    ->field('name,area,addr')
                    ->find();
                if($ret){
                    $v['name'] = $ret['name'];
                    $v['area'] = $ret['area'];
                    $v['addr'] = $ret['addr'];
                    $list[$k] = $v;
                }else{
                    $v['name'] = '';
                    $v['area'] = '';
                    $v['addr'] = '';
                    $list[$k] = $v;
                }
            }
        }

        $data = $list->all();
        $time = time();
        foreach ($data  as $k=>$v) {
            $data2 = Cache::store('redis')->get($v['cabinet_id']);
            isset($data2['heartbeattime'])?$v['heartbeattime']=$data2['heartbeattime']:$v['heartbeattime']='';
            isset($data2['clientip'])?$v['clientip']=$data2['clientip']:$v['clientip']='';
            $v['times'] = $time - $v['heartbeattime'];
            $list[$k] = $v;
        }

        //var_dump($list);die;

        //var_dump($list);die;
        //$this->assign('page', $page);
        $this->assign('list',$list);
        $ret = Db::name('operator')
            ->where(['is_delete'=>1,'status'=>1])
            ->order('create_time desc')
            ->select();
        $this->assign('operator',$ret);
        return $this->fetch();
    }
    public function add(){

        if ( Request::instance()->isPost()) {
            $data = input('post.');
            $data['create_user'] = session('adminid');
            $data['create_time'] = time();
            $data['is_delete'] = 1;
            $validate = \think\Loader::validate('Charecabinet');
            if(!$validate->scene('add')->check($data)){
                $this->error(lang($validate->getError()));
                //return ['code'=>-1050, 'msg'=>'请仔细检查是否有没有填写的地方!'];
            }
            if($data['cabinet_id']=='' || $data['oid']=='' || $data['sid']=='' || $data['model']=='' || $data['devicenum']==''){
                return ['code'=>-1050, 'msg'=>lang('请仔细检查是否有没有填写的地方')];
            }
            if(Db::name('charecabinet')->insert($data)){
                //直营商1/代理商大于1
                $oid = 1;$m = 'ausadmin'; $c = 'Equipment'; $action="add"; $uid=session('adminid'); $querystring = '添加'.input('cabinet_id').'机柜信息';
                $ip = get_ip();$os = get_os();
                set_logs($oid,$m,$c,$action,$uid,$querystring,$ip,$os);
                return  ['code'=>1, 'msg'=>lang('添加机柜信息成功！')];
            }else{
                return ['code'=>-1050, 'msg'=>lang('添加机柜信息失败！')];
            }
            //return;
            //var_dump($data); die;

        }else{
            $where = 'is_delete=1';
            $operator = Db::name('operator')->where('is_delete',1)->order('create_time desc')->select();
            $this->assign('ret',$operator);
            return $this->fetch();
        }

    }

    public function details(){
        $id = Request::instance()->get('id','','number_int');
        //echo $id; die;
        $data = DB::name('charecabinet')
            ->where('id',$id)
            ->find();
        //cabinet_id	
        $cabinet_id = $data['cabinet_id'];
        $Send = new Send($cabinet_id);
        $stockDetail = $Send->StockDetail();//获取库存明细
        $data = array(
            'stockDetail'      => $stockDetail,
        );
        /*$logdata = array(
            'oid' => 0,//直营商1/代理商大于1/管理员0
            'mode' => 2,
            'operation' => 6,
            'info' => '',
            'resstatus'=> $stockDetail['types'],
            'result' => $stockDetail['info'],
            'create_user'  => session('adminid'),
          );
          isset($stockDetail['hex'])? $logdata['reshex']=$stockDetail['hex']:'';
          $Send->Log($logdata);//记录机柜日志*/
        //var_dump($stockDetail);die;
        $this->assign('data',$data);
        $this->assign('cabinet_id',$cabinet_id);
        return $this->fetch('../application/publicview/equipment/details.html');
    }

    //以下是充电宝有关的信息
    public function electricize(){
        $pages = 20;
        $where = 'a.is_delete=1 ';
        $user = Config::get('auth.table_user');
        if(!empty(input('deviceid'))){
            $where .= ' AND a.device_id LIKE '."'%".input('deviceid')."%' ";
        }
        $list = DB::name('portablebattery')
            ->alias('a')
            ->join("$user b",'a.create_user = b.id')
            ->join("operator o", 'a.oid = o.id', 'LEFT')
            ->field('a.id, o.name as operator_name,a.device_id,a.create_user,a.status,a.create_time,b.username,b.name,b.phone')
            ->where($where)
            ->order('a.create_time desc')
            ->paginate($pages);

        $this->assign('list',$list);

        return $this->fetch('../application/publicview/equipment/electricize.html');
    }

    public function record(){
        $pages = 20;
        $where = 'a.is_delete=1';
        if(!empty(input('deviceid'))){

            $where .= ' AND b.deviceid LIKE '."'%".input('deviceid')."%' ";
            //$pageParam['query']['b.name'] = input('name');
        }
        $a = 'leaseorder';//租借记录表
        $list = DB::name('portablebattery')
            ->alias('a')
            ->join("$a b",'a.device_id = b.deviceid')
            ->field("ifnull(count(b.deviceid),0) as amount,a.device_id ,a.id")
            ->where($where)
            ->group('a.device_id,a.id')
            ->paginate($pages);
        //var_dump($list);die;   
        //echo Db::name('portablebattery')->getlastsql();   
        $this->assign('list',$list);
        return $this->fetch('../application/publicview/equipment/record.html');
    }

    //生成二维码
    public function createqrcode($id=null,$oid='')
    {
        ob_clean();
        //$oid = Request::instance()->get('oid','','number_int');//直营商1/代理商大于1
        if($id){

            /*$oid = 1;//直营商1
            $oid2 = mwencrypt((string)$oid);*/
            $cid = $id;
            $website = config('qrcodeurl');

            //$data = '/Lease?cineda='.$cid;
            $data = $cid;
            $url = $website .$data;


            $errorCorrectionLevel = 'L';//容错级别
            $matrixPointSize = intval(18);//生成图片大小
            //生成二维码图片
            Loader::import('qrcode.phpqrcode');
            $object = new \QRcode();

            $filename = 'qrcode/'.microtime().'.png';

            $object->png($url, $filename, $errorCorrectionLevel, $matrixPointSize, 2);

            /*$logo = DB::name('operator')
                ->where('id',$oid)
                ->cache(true)
                ->find();*/
            $QR = $filename;//已经生成的原始二维码图 
            $QR = imagecreatefromstring(file_get_contents($QR)); //打开文件
            //如果有logo则将LOGO合并
            /*if ($logo != '') { 

                $logo = $website.$logo['logo']; //连接完整的logo地址
                
                $logo = imagecreatefromstring(file_get_contents($logo)); 
                $QR_width = imagesx($QR);//二维码图片宽度 
                $QR_height = imagesy($QR);//二维码图片高度 
                $logo_width = imagesx($logo);//logo图片宽度 
                $logo_height = imagesy($logo);//logo图片高度 
                $logo_qr_width = $QR_width / 5; 
                $scale = $logo_width/$logo_qr_width; 
                $logo_qr_height = $logo_height/$scale; 
                $from_width = ($QR_width - $logo_qr_width) / 2; 
                //重新组合图片并调整大小 
                imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width, 
                $logo_qr_height, $logo_width, $logo_height); 
                
            }*/
            //输出图片 
            Header("Content-type: image/png");
            ImagePng($QR,'qrcode/qrcode.png');
            imagedestroy($QR);
            $qrcode =  '<img src="/qrcode/qrcode.png" alt="" width="200px" >';
            echo $qrcode;

        }
    }
    //查询可借可充充电宝数量
    public function totales($cabinet_id=''){
        $cabinet_id = input('param.cabinet_id');
        $Send = new Send($cabinet_id);
        $totals = $Send->StockNum();//获取总库存量
        isset($totals['info'])?$total=$totals['info']:$total='';
        isset($totals['types'])?$type=$totals['types']:$type='';

        $devicenum = Db::name('charecabinet')->where(['cabinet_id' => $cabinet_id, 'is_delete' => 1])->field('cabinet_id, devicenum')->find();

        if($type){
            /*$logdata = array(
                'oid' => 0,
                'mode' => 2,
                'operation' => 'StockNum',
                'info' => '',
                'result' => $totals,
                'create_user'  => session('adminid'),
              );
              isset($totals['hex'])? $logdata['reshex']=$totals['hex']:'';
              $Send->Log($logdata);*///记录机柜日志

            return ['code'=>0, 'msg'=> $total, 'devicenum'=>$devicenum['devicenum']];
        }else{
            return ['code'=>1, 'msg'=>'', 'devicenum'=>$devicenum['devicenum']];
        }

    }
    //查询iccid
    public function iccid($cabinet_id=''){
        $cabinet_id = input('param.cabinet_id');
        $Send = new Send($cabinet_id);
        $totals = $Send->ICCID();//获取总库存量
        isset($totals['info'])?$total=$totals['info']:$total='';
        isset($totals['types'])?$type=$totals['types']:$type='';

        if($type){
            return ['code'=>0, 'msg'=> $total];
        }else{
            return ['code'=>1, 'msg'=>''];
        }

    }
    //更新机柜信息
    public function edit($id=""){

        if ( Request::instance()->isPost() ) {
            $data = input('post.');
            $validate = \think\Loader::validate('Charecabinet');
            if(!$validate->scene('edit')->check($data)){
//            $this->error($validate->getError());
                return ['code'=>-1050, 'msg'=>lang($validate->getError())];
            }
            if($data['sid']=='' || $data['oid']=='' || $data['model']=='' || $data['devicenum']==''){
                return ['code'=>-1050, 'msg'=>lang('请仔细检查是否有没有填写的地方')];
            }

            //var_dump($data);die;
            if(Db::name( 'charecabinet')->update($data)){
                //直营商1/代理商大于1
                $oid = 1;$m = 'ausadmin'; $c = 'Equipment'; $action="edit"; $uid=session('adminid'); $querystring = '更新设备'.input('id').'信息';
                $ip = get_ip();$os = get_os();
                set_logs($oid,$m,$c,$action,$uid,$querystring,$ip,$os);
                return ['code'=>0, 'msg'=>lang('修改成功！')];
            }else{
                return ['code'=>-1050, 'msg'=>lang('修改失败！')];
            }
            //return;
        }else{
            $where['id'] = $id;
            $charecabinet = Db::name('charecabinet')->where($where)->find();
            /*$where2['is_delete'] = 1;

            $where2['status'] = 1;
            $list = Db::name('seller')
                ->field('id,name')
                ->where($where2)
                ->select();*/
            $olist = Db::name('operator')->where(['is_delete'=>1,'status'=>1])->select();
            $clist = Db::name('seller')->where(['oid'=>$charecabinet['oid'],'is_delete'=>1])->select();
            $this->assign('list',$clist);
            $this->assign('o',$olist);
            $this->assign('v',$charecabinet);

            return $this->fetch();

        }

    }

    //更新充电宝信息
    public function editbattery($id=""){

        if ( Request::instance()->isPost() ) {
            $data = input('post.');
            if($data['oid']==''){
                return ['code'=>-1050, 'msg'=>lang('内容不能为空！')];
            }

            if(Db::name( 'portablebattery')->update($data)){
                //$this->redirect('index');
                $oid = 1;$m = 'ausadmin'; $c = 'Equipment'; $action="editbattery"; $uid=session('adminid'); $querystring = '更新充电宝信息';
                $ip = get_ip();$os = get_os();
                set_logs($oid,$m,$c,$action,$uid,$querystring,$ip,$os);
                return ['code'=>0, 'msg'=>lang('修改成功！')];
            }else{
                return ['code'=>-1050, 'msg'=>lang('修改失败！')];
            }
            //return;
        }else{
            $where['id'] = $id;
            $portablebattery = Db::name('portablebattery')->where($where)->find();
            $olist = Db::name('operator')->where(['is_delete'=>1,'status'=>1])->select();
            $this->assign('o',$olist);
            $this->assign('v',$portablebattery);

            return $this->fetch();
        }
    }

    //删除机柜信息
    public function delete($id=""){
        $id =  Request::instance()->get('id','','number_int');
        if($id){
            $data['id'] = $id;
            $data['is_delete'] =0;
            if(Db::name( 'charecabinet')->update($data)){
                //$this->redirect('index');
                //直营商1/代理商大于1
                $oid = 1;$m = 'ausadmin'; $c = 'Equipment'; $action="delete"; $uid=session('adminid'); $querystring = '删除机柜'.$id.'信息';
                $ip = get_ip();$os = get_os();
                set_logs($oid,$m,$c,$action,$uid,$querystring,$ip,$os);
                return ['code'=>0, 'msg'=>lang('删除成功！')];
            }else{
                return ['code'=>-1050, 'msg'=>lang('删除失败！')];
            }

        }
    }

    //删除充电宝信息
    public function deletebattery($id=""){
        $id =  Request::instance()->get('id','','number_int');
        if($id){
            $data['id'] = $id;
            $data['is_delete'] =0;
            if(Db::name( 'portablebattery')->update($data)){
                //$this->redirect('index');
                $oid = 1;$m = 'ausadmin'; $c = 'Equipment'; $action="delete"; $uid=session('adminid'); $querystring = '删除充电宝'.$id.'信息';
                $ip = get_ip();$os = get_os();
                set_logs($oid,$m,$c,$action,$uid,$querystring,$ip,$os);
                return ['code'=>0, 'msg'=>lang('删除成功！')];
            }else{
                return ['code'=>-1050, 'msg'=>lang('删除失败！')];
            }

        }
    }    

    //查看机柜配置信息
    /*public function configure($cabinet_id=''){
    	$cabinet_id = input('param.cabinet_id');
    	$Send = new Send($cabinet_id);
    	if(!empty($cabinet_id)){
    		$config = $Send->GetConfigure();//获取总库存量//新机柜无此功能
    		$logdata = array(
				'oid' => 0,//直营商1/代理商大于1
				'mode' => 2,
				'operation' => 7,
				'resstatus'=> $config['types'],
				'info' => '',
				'result' => $config['info'],
				'create_user'  => session('adminid'),
			);
		  	isset($config['hex'])? $logdata['reshex']=$config['hex']:'';
			$Send->Log($logdata);//记录机柜日志
			if($config['types']){
				$configures = $config['info'];
				$oid = session('oid');$m = 'ausadmin'; $c = 'Equipment'; $action="configure"; $uid=session('adminid'); $querystring = '获取设备'.$cabinet_id.'配置信息';
		        $ip = get_ip();$os = get_os();
		        set_logs($oid,$m,$c,$action,$uid,$querystring,$ip,$os);
				$this->assign('v',$configures);
			}else{
				$data = '暂无设备配置信息';
				$this->assign('view',$data);
			}	
    	}
		
		//var_dump($config);die;
		
		return $this->fetch('../application/publicview/equipment/configure.html');
    }*/

    //查看版本信息
    public function version(){
        $cabinet_id = input('param.cabinet_id');
        $Send = new Send($cabinet_id);
        if(!empty($cabinet_id)){
            $version = $Send->Version();//获取版本号
            /*$logdata = array(
                'oid' => 0,//直营商1/代理商大于1
                'mode' => 2,
                'operation' => 8,
                'resstatus'=> $version['types'],
                'info' => '',
                'result' => $version['info'],
                'create_user'  => session('adminid'),
            );
              isset($version['hex'])? $logdata['reshex']=$version['hex']:'';
            $Send->Log($logdata);//记录机柜日志*/
            if($version['types']){

                $versions = $version['info'];
                $this->assign('v',$versions);
            }else{
                $data = '暂无设备版本信息';
                $this->assign('view',$data);
            }
        }
        $oid = 1;$m = 'ausadmin'; $c = 'Equipment'; $action="version"; $uid=session('adminid'); $querystring = '查看设备'.$cabinet_id.'版本信息';
        $ip = get_ip();$os = get_os();
        set_logs($oid,$m,$c,$action,$uid,$querystring,$ip,$os);
        return $this->fetch('../application/publicview/equipment/version.html');
    }
    //重启设备
    public function restart(){
        $id = input('param.cabinet_id');
        if(!empty($id)){
            $this->assign('id',$id);
            return $this->fetch('../application/publicview/equipment/restart.html');
        }
        if(input('id')){
            $id = input('param.id');
            //var_dump($id);die;
            $Send = new Send($id);
            $result = $Send->Restart();
            /*$logdata = array(
                'oid' => 0,
                'mode' => 2,
                'operation' => 5,
                'resstatus'=> $result['types'],
                'info' => '',
                'result' => $result['info'],
                'create_user'  => session('adminid'),
            );
              isset($result['hex'])? $logdata['reshex']=$result['hex']:'';
            $Send->Log($logdata);//记录机柜日志*/
            if($result['types']==1){
                //直营商1/代理商大于1
                $oid = 1;$m = 'ausadmin'; $c = 'Equipment'; $action="restart"; $uid=session('adminid'); $querystring = '重启设备'.$id;
                $ip = get_ip();$os = get_os();
                set_logs($oid,$m,$c,$action,$uid,$querystring,$ip,$os);
                return ['code'=>0, 'msg'=>lang('重启成功！')];
            }else{
                return ['code'=>-1050, 'msg'=>lang('重启失败！')];
            }
        }




    }

    public function updateconf(){

        if ( Request::instance()->isPost() ) {
            //var_dump(input('post.'));die;
            $data = input('post.');
            //验证
            $validate = new Validate();
            $validate -> rule([
                ['cabinet_id','require','缺少参数机柜id'],
                ['servicer','require','缺少参数服务器地址'],
                ['port','require','缺少参数服务器端口'],
                ['heartbeat','require','缺少参数心跳'],
            ]);
            $result = $validate->check($data);
            if(!$result){
                return ['code'=>-1051, 'msg'=>$validate->getError()];
            }

            $cabinet_id = $data['cabinet_id'];
            $addr = $data['servicer'];
            $port = $data['port'];
            $heartbeat = $data['heartbeat'];
            $Send = new Send($cabinet_id);
            $setconfig = $Send->UpdateStatus($addr,$port,$heartbeat);
            /*$logdata = array(
                'oid' => 0,
                'mode' => 2,
                'operation' => 3,
                'info' =>   json_encode(array(
                     'addr' =>$addr, 
                       'port' =>$port,
                       'heartbeat' =>$heartbeat , 
                )),
                'resstatus'=> $setconfig['types'],
                'result' => $setconfig['info'],
                'create_user'  => session('adminid'),
            );
              isset($setconfig['hex'])? $logdata['reshex']=$setconfig['hex']:'';
            $Send->Log($logdata);//记录机柜日志*/
            if($setconfig['types']){

                $oid = 1;$m = 'ausadmin'; $c = 'Equipment'; $action="updateconf"; $uid=session('adminid'); $querystring = '更新设备'.$cabinet_id.'配置信息';
                $ip = get_ip();$os = get_os();
                set_logs($oid,$m,$c,$action,$uid,$querystring,$ip,$os);
                return ['code'=>0, 'msg'=>lang('更新成功！')];
            }else{
                return ['code'=>-1050, 'msg'=>lang('更新失败！')];
            }


        }else{
            $cabinet_id = input('param.cabinet_id');
            /*$Send = new Send($cabinet_id);
            $config = $Send->GetConfigure();*/
            if(!empty($cabinet_id)){
                /*if($config){
                    $logdata = array(
                        'oid' => 0,
                        'mode' => 2,
                        'operation' => 7,
                        'info' => '',
                        'resstatus'=> $config['types'],
                        'result' => $config['info'],
                        'create_user'  => session('adminid'),
                      );
                      isset($config['hex'])? $logdata['reshex']=$config['hex']:'';
                      $Send->Log($logdata);//记录机柜日志
                    $configures = $config['info'];
                    $this->assign('con',$configures);
                }*/

                $this->assign('v',$cabinet_id);
                return $this->fetch('../application/publicview/equipment/updateconf.html');
            }
        }
    }

    public function info(){

        if ( Request::instance()->isPost() ) {
            $cabinet_id = input('param.cabinet_id');//充电宝ID
            $lockid = input("param.lockid");//锁ID
            if(!empty($cabinet_id)){
                $Send = new Send($cabinet_id);
                $ret = $Send->EjectDevice($lockid);//弹出指定充电宝
                /*$logdata = array(
                    'oid' => 0,
                    'mode' => 2,
                    'operation' => 1,
                    'info' => $lockid,
                    'resstatus'=> $ret['types'],
                    'result' => $ret['info'],
                    'create_user'  => session('adminid'),
                );
                isset($ret['hex'])? $logdata['reshex']=$ret['hex']:'';
                $Send->Log($logdata);//记录机柜日志*/
                if($ret['types']){

                    $oid = 1;$m = 'ausadmin'; $c = 'Equipment'; $action="info"; $uid=session('adminid'); $querystring = '弹出充电宝'.$cabinet_id.'所在锁ID'.$lockid;
                    $ip = get_ip();$os = get_os();
                    set_logs($oid,$m,$c,$action,$uid,$querystring,$ip,$os);
                    return ['code'=>0, 'msg'=>lang('弹出充电宝成功！')];
                }else{
                    return ['code'=>-1050, 'msg'=>lang('弹出充电宝失败！')];
                }
            }
        }else{
            $batteryid = input('param.batteryid');
            $key = input('param.key');
            $power = input('param.power');
            $cabinetid = input("param.cabinetid");
            $data  = array(
                'cabinetid' => $cabinetid,
                'key' => $key,
                'power' => $power,
                'batteryid' => $batteryid,

            );
            $this->assign("data",$data);
            $oid = 1;$m = 'ausadmin'; $c = 'Equipment'; $action="info"; $uid=session('adminid'); $querystring = '查看充电宝'.$batteryid.'信息';
            $ip = get_ip();$os = get_os();
            set_logs($oid,$m,$c,$action,$uid,$querystring,$ip,$os);
            return $this->fetch('../application/publicview/equipment/info.html');
        }

    }
    public function ota(){
        $pages = 20;
        $did = Request::instance()->get('did','','number_int');
        if(!empty($did)){
            //var_dump($did);die;
            $data['id'] = $did;
            $data['is_delete'] = 0;
            if(Db::name( 'charecabinet_version')->update($data)){
                //$this->redirect('index');
                $oid = 1;$m = 'ausadmin'; $c = 'Equipment'; $action="ota"; $uid=session('adminid'); $querystring = '删除设备升级包'.$did.'信息';
                $ip = get_ip();$os = get_os();
                set_logs($oid,$m,$c,$action,$uid,$querystring,$ip,$os);
                return ['code'=>0, 'msg'=>lang('删除成功！')];
            }else{
                return ['code'=>-1050, 'msg'=>lang('删除失败！')];
            }
        }
        if ( Request::instance()->isPost() ) {
            $path = 'uploads/ota/';
            if($_FILES['file']['name']){
                $path = 'uploads/ota/';
                $file = Request::instance()->file('file');
                $file_info = $file->move($path,'');
                $filename = $file_info->getSaveName();
                $source = ROOT_PATH . 'public' . DS . 'uploads'.DS.'ota'.DS.$file_info->getSaveName();//本地文件
                $FTP_HOST = config('ftp.addr');//ftp服务器地址
                $FTP_PORT = config('ftp.port');  //ftp端口
                $FTP_USER = config('ftp.username');//ftp用户名
                $FTP_PASS = config('ftp.password');//ftp用户密码
                $conn = ftp_connect($FTP_HOST,$FTP_PORT)  or die("Could not connect"); // 联接FTP服务器 	
                ftp_login($conn, $FTP_USER,$FTP_PASS); // 使用username和password登录 
                ftp_pasv($conn,TRUE);//
                if(ftp_put($conn,"$filename","$source",FTP_ASCII)){
                    $data['file_name'] = $filename;
                    $data['create_time'] = time();
                    $data['create_user'] = session('adminid');
                    $data['is_delete'] = 1;
                    Db::name('charecabinet_version')->insert($data);
                    unlink($source);//删除文件
                    $oid = 0;$m = 'ausadmin'; $c = 'Ftp'; $action="index"; $uid=session('adminid'); $querystring = '上传机柜版本文件'.$filename;
                    $ip = get_ip();$os = get_os();
                    set_logs($oid,$m,$c,$action,$uid,$querystring,$ip,$os);
                    ftp_quit($conn);//关闭连接
                    return ['code'=>0,'msg'=>lang('上传成功！')];
                } else{
                    return ['code'=>-1050,'msg'=>lang('上传失败！')];
                }
                // $file = Request::instance()->file('file');
                // //var_dump($file);
                // $file_info = $file->move($path,'');
                // $file_info = $file_info->getSaveName();
                // $info = $file_info;
                // $file_info = $path.$file_info;//var_dump($file_info);die;
                // $data2['file'] = '/'.$file_info;

                // Loader::import('ftp.ftp');
                // $ftp = new \Ftp();
                // var_dump($ftp);
                // return $ftp->index();
                /*
                //服务器地址(IP or domain)
                $data['server'] = config('ftp.addr');
                //ftp帐户
                $data['username'] = config('ftp.username');
                $data['password'] =config('ftp.password');
                $user = $data['username'];
                $pwd = $data['password'];
                //ftp密码

                //ftp端口,默认为21
                $data['port'] = config('ftp.port');
                
                //var_dump($data['file']);die;
                //$con = $ftp->start($data);
                $remote = $info;
                $local = $_SERVER['DOCUMENT_ROOT'].'/uploads/ota/'.$info;
                $source = @fopen("$local","r");
                $conn = ftp_connect($data['server'],$data['port'],30) or die("Could not connect");
                
                @ftp_login($conn,"$user","$pwd");

                //var_dump(ftp_pwd($conn));

                //是否开启被动模式,true开启,默认不开启
                @ftp_pasv($conn, true);

                //$result = ftp_put($conn,"$remote",$source,FTP_ASCII);
                $result = ftp_put($conn,"$remote",$local,FTP_BINARY, 0);
                if ($result) {
                    
                }
                     */           
                //var_dump($result);

            }
            //return ['code'=>-1050, 'msg'=>'上传失败'];
        }
        $version=Db::name('charecabinet_version')
            ->where('is_delete',1)
            ->order('create_time DESC')
            ->paginate($pages);
        $this->assign('list',$version);
        return $this->fetch('../application/publicview/equipment/ota.html');
    }

    public function otadd(){
        return $this->fetch('../application/publicview/equipment/otadd.html');
    }

    public function updatestatus(){
        if ( Request::instance()->isPost() ) {
            $filename = input('file_name');
            $cabinet_id = input('cabinet_id');
            $addr = config('ftp.addr');
            $port = config('ftp.port');
            $username = config('ftp.username');
            $password = config('ftp.password');
            $data = array(
                'filename' 		=>      $filename,
                'cabinet_id'  	=>		$cabinet_id,
                'addr'			=>		$addr,
                'port'			=>		$port,
                'username'		=>		$username,
                'password'		=>		$password,

            );
            var_dump($data);die;
        }else{
            $cabinet_id = input('param.cabinet_id');
            $version=Db::name('charecabinet_version')
                ->where('is_delete',1)
                ->select();
            $this->assign('list',$version);
            $this->assign('id',$cabinet_id);
            return $this->fetch('../application/publicview/equipment/updatestatus.html');
        }
    }
    public function openalock(){

        if ( Request::instance()->isPost() ) {
            //var_dump(input('post.'));die;
            $cabinet_id = input('param.cabinet_id');
            $lockid = input("param.lockid");

            $Send = new Send($cabinet_id);
            $result = $Send->EjectDevice($lockid);

            if($result['types']==1){


                return ['code'=>0, 'msg'=>lang('弹出成功！')];
            }else{
                return ['code'=>-1050, 'msg'=>lang('弹出失败！')];
            }


        }else{
            $cabinet_id = input('param.cabinet_id');

            if(!empty($cabinet_id)){

                $this->assign('v',$cabinet_id);
                return $this->fetch();
            }
        }
    }
    public function openalllock(){

        $id = input('param.cabinet_id');
        if(!empty($id)){
            $this->assign('id',$id);
            return $this->fetch();
        }
        if(input('param.id')){
            $id = input('param.id');
            //var_dump($id);die;
            $Send = new Send($id);
            $result = $Send->OpenAllLock();

            if($result['types']==1){
                return ['code'=>0, 'msg'=>lang('弹出成功！')];
            }else{
                return ['code'=>-1050, 'msg'=>lang('弹出失败！')];
            }
        }

    }
    //充电宝记录及查询充电次数
    public function portablebattery(){
        $where = 'status = 1 AND is_delete = 1';
        $pages = 20;
        $pageParam    = ['query' =>[]];
        if(!empty(input('device_id'))){
            $where .= ' AND device_id LIKE '."'%".input('device_id')."%' ";
            $pageParam['query']['device_id'] = input('device_id');
        }

        $list = Db::name('portablebattery')
            ->where($where)
            ->order('create_time desc')
            ->paginate($pages,false, $pageParam);
        $data = $list->all();
        foreach ($data  as $k=>$v) {
            $ret = Db::name('leaseorder')
                ->where('deviceid',$v['device_id'])
                ->count();
            if($ret){
                $v['num'] = $ret;
                $list[$k] = $v;
            }else{
                $v['num'] = '暂无记录';
                $list[$k] = $v;
            }
        }
        //var_dump($list);die;
        $this->assign('list',$list);
        $oid = 1;$m = 'ausadmin'; $c = 'Equipment'; $action="portablebattery"; $uid=session('adminid'); $querystring = '查看充电宝充电次数列表';
        $ip = get_ip();$os = get_os();
        set_logs($oid,$m,$c,$action,$uid,$querystring,$ip,$os);
        return $this->fetch();
    }
    //日志
    public function log(){
        //oid为0的，查总管理表
        //oid为其他数字，mode为2的查询运营商管理表（如果有openid，这位移动端操作）
        //mode等于1的，查询用户表。
        //
        $pages = 20;
        $where = '';
        $pageParam    = ['query' =>[]];
        if(!empty(input('cabinet_id'))){
            //$where .= ' cabinet_id LIKE '."'%".input('cabinet_id')."%' ";
            $where['cabinet_id'] = ['like','%'.input('cabinet_id').'%'];
            $pageParam['query']['cabinet_id'] = input('cabinet_id');
            $this->assign('jgid',input('cabinet_id'));
        }
        if(!empty(input('operatorname'))){
            $name = input('operatorname');
            if($name=='总管理员'){
                $where['oid'] = 0;
            }else{
                $where1 = ' b.name LIKE '."'%".input('operatorname')."%' ";
                $where['oid'] = ['>',0];
            }
            $pageParam['query']['operatorname'] = input('operatorname');
            $this->assign('operatorname',input('operatorname'));
        }
        if(!empty(input('mode'))){
            //echo input('mode');die;
            $mode = (int)input('mode');
            $where['mode'] = "$mode";
            $pageParam['query']['mode'] = input('mode');
            $this->assign('mode',input('mode'));
        }

        if(!empty(input('resstatus'))){
            //echo input('resstatus');die;
            $resstatus = (int)input('resstatus');
            if($resstatus){
                $where['resstatus'] = "$resstatus";
            }else{
                $where['resstatus'] = ['<>',1];
            }

            $pageParam['query']['resstatus'] = input('resstatus');
            $this->assign('resstatus',input('resstatus'));
        }
        if(!empty(input('param.starttime')) and !empty(input('param.endtime'))){
            $starttime = strtotime(input('param.starttime'));
            $endtime = strtotime(input('param.endtime'));
            $this->assign('kaishitime',input('starttime'));
            $this->assign('jieshutime',input('endtime'));
            $pageParam['query']["starttime"] = input('param.starttime');
            $pageParam['query']["endtime"] = input('param.endtime') ;
            $list = Db::name('charecabinet_log')
                ->where($where)
                ->whereTime('create_time','between', [$starttime, $endtime])
                ->order('create_time desc')
                ->paginate($pages, false, $pageParam);
            //echo Db::name('charecabinet_log')->getlastsql();die;
            //SELECT * FROM `charecabinet_log` WHERE `create_time` BETWEEN 1505145600 AND 1505438726 ORDER BY create_time desc LIMIT 0,20
        }else{
            $list = Db::name('charecabinet_log')->where($where)->order('create_time desc')->paginate($pages, false, $pageParam);
            //echo Db::name('charecabinet_log')->getlastsql();die;
        }

        //var_dump($list);
        //echo Db::name('charecabinet_log')->getlastsql();
        $data = $list->all();
        $o ='operator';
        foreach ($data  as $k=>$v) {
            if($v['oid']==0){ //总管理员
                $data2 = Db::name('admin')->where(['id'=>$v['create_user'],])->find();
                $v['name'] = $data2['username'];
                $v['yys'] = 0;
                $list[$k] = $v;
            }else{
                if($v['mode']==2){ //运营商后台操作
                    /*$data2 = Db::name('operator')->where('id',$v['create_user'])->find();
                    $v['name'] = $data2['username'];*/
                    if(isset($where1)){
                        $data2 = Db::name('operator_users')
                            ->alias('a')
                            ->join("$o b",'a.oid = b.id')
                            ->where($where1)
                            ->where('a.id',$v['create_user'])
                            ->field('a.username,b.name')
                            ->find();
                        if($data2){
                            $v['name'] = $data2['username'];
                            $v['yys'] = $data2['name'];
                            $list[$k] = $v;
                        }else{
                            $list= array();
                        }

                    }else{
                        $data2 = Db::name('operator_users')
                            ->alias('a')
                            ->join("$o b",'a.oid = b.id')
                            ->where('b.id',$v['oid'])
                            ->where('a.id',$v['create_user'])
                            ->field('a.username,b.name')
                            ->find();
                        $v['name'] = $data2['username'];
                        $v['yys'] = $data2['name'];
                        $list[$k] = $v;
                    }


                }else{//运营端用户下单
                    $data2 = Db::name('user')
                        ->alias('a')
                        ->join("$o b",'a.oid = b.id')
                        ->where('b.id',$v['oid'])
                        ->where('a.id',$v['create_user'])
                        ->field('a.name,b.name as yyas')
                        ->find();
                    $v['name'] = $data2['name'];
                    $v['yys'] = $data2['yyas'];
                    $list[$k] = $v;
                }
            }
        }

        $this->assign('list',$list);
        return $this->fetch();

    }
    public function command(){
        if ( Request::instance()->isPost() ) {
            $types = Request::instance()->post('types');
            $cabinet_id = Request::instance()->post('cabinet_id');  //机柜ID


            $aaa = Cache::store('redis')->get($cabinet_id);
            dump($aaa);


            if(Request::instance()->has('lockid','post')){
                $lockid = Request::instance()->post('lockid');  //锁ID
            }else{
                $lockid = false;
            }


            $str = $types.",".$cabinet_id;
            if($lockid){
                $str.=",".$lockid;
            }

            if($types=='202'){

                $addr = Request::instance()->post('addr');  //服务器地址
                $str.=",".$addr;
                $port = Request::instance()->post('port');  //端口
                $str.=",".$port;
                $heartbeat = Request::instance()->post('heartbeat');  //心跳
                $str.=",".$heartbeat;

            }else if($types=='203'){
                $delayed = Request::instance()->post('delayed');  //延迟
                $str.=",".$delayed;
            }else if($types=='204'){
                $addr = Request::instance()->post('addr');  //服务器地址
                $str.=",".$addr;
                $port = Request::instance()->post('port');  //端口
                $str.=",".$port;
                $filename = Request::instance()->post('filename');  //文件名
                $str.=",".$filename;
                $username = Request::instance()->post('username');  //文件名
                $str.=",".$username;
                $password = Request::instance()->post('password');  //文件名
                $str.=",".$password;
            }

//	        $str.="\n";

            $client = stream_socket_client(config('tcpintraneturl'));
            if(!$client)exit("can not connect");
            // 模拟超级用户，以文本协议发送数据，注意Text文本协议末尾有换行符（发送的数据中最好有能识别超级用户的字段），这样在Event.php中的onMessage方法中便能收到这个数据，然后做相应的处理即可

            $service = 'service';
            $time = time();
            $key = md5(config('headerkey').$time);
            $data = $service.','.$key.','.$time.','.$str;
            fwrite($client, $data);

//            fwrite($client, $str);
        }
        return $this->fetch();

    }
    //实时监控
    public function monitor(){
        $time = time();
        $this->assign('listenurl',config('tcplistenurl'));
        $this->assign('key',md5(config('headerkey').$time));
        $this->assign('time',$time);
        return $this->fetch();

    }

    //获取指定运营商下的商户 -> 改为代理商下的商户
    public function sellers(){
        if ( Request::instance()->isPost() ) {
            $oid = (int)input('oid');
            if($oid){
                $ret = Db::name('seller')->where(['oid'=>$oid,'is_delete'=>1])->select();
                $data = '<option value="">选择商户</option>';
                $li = '<li class="active-result result-selected" data-option-array-index="0" style="">选择商户</li>';
                if($ret){
                    foreach($ret as $k => $v){
                        $data .='<option value="'.$v['id'].'">'.$v['name'].'</option>';
                        $li .= '<li class="active-result" data-option-array-index="'.$k.'">'.$v['name'].'</li>';
                    }
                }else{
                    $data .= '<option value="">暂无商户</option>';
                    $li .= '';
                }
                $datas = json_encode($data);
                $datas = json_decode($datas);
                $list = json_encode($li);
                $li = json_decode($list);
                return ['code'=>0, 'msg'=>"$datas",'li'=>"$li"];
                //ajaxReturn($data,'',1);
                //return json_decode($data);
            }else{
                return ['code'=>-1050, 'msg'=>lang('非法传参！')];
            }
        }else{
            die('非法访问!已被拦截!');
        }
    }

}